package com.ebelter.temperaturegun.model.http;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.ebelter.btcomlib.models.beans.UpdateVersionBean;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.utils.AppUtils;
import com.ebelter.btcomlib.utils.FileUtils;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;

import com.ebelter.temperaturegun.ui.activity.AboutActivity;
import com.lzy.okgo.callback.FileCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import okhttp3.Call;
import okhttp3.Response;


public class TemUpdateService extends Service {
    public static final String TAG="TemUpdateService";

    public static boolean isDownLoading=false;
    public static final String DownloadSer="DownloadPath";




    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isDownLoading){
            boolean hasExtra = intent.hasExtra(DownloadSer);
            if (!hasExtra){
                return super.onStartCommand(intent, flags, startId);
            }
            UpdateVersionBean updateVersionBean = (UpdateVersionBean) intent.getSerializableExtra(DownloadSer);

            if (updateVersionBean==null){
                return super.onStartCommand(intent, flags, startId);
            }else {
                LogUtils.i(TAG,"----onStartCommand-"+updateVersionBean.toString());

                File file=getSaveApk(updateVersionBean);

                boolean isFileDownLoaded = judgeFileDownLoaded(updateVersionBean,file.getAbsoluteFile());

                if (isFileDownLoaded){

                    AppUtils.installApp(getApplicationContext(),file.getAbsolutePath(),"com.ebelter.tem.fileprovider");
                }else {


                    String downloadPath=getDownLoadFilePath(updateVersionBean);
                    NetUtils.getInstance().getFileDownLoad(this, downloadPath, new FileCallback(file.getParent(),file.getName()) {
                        @Override
                        public void onSuccess(File file, Call call, Response response) {
                            isDownLoading=false;
                            if (file!=null&&file.getAbsolutePath().endsWith(".apk")){
                                AppUtils.installApp(getApplicationContext(),file.getAbsolutePath(),"com.ebelter.tem.fileprovider");
                                LogUtils.i(TAG,"----下载完成---"+file.getAbsolutePath());
                            }


                        }
                        @Override
                        public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                            super.downloadProgress(currentSize, totalSize, progress, networkSpeed);
                            isDownLoading=true;
                            LogUtils.i(TAG,"----下载中---currentSize="+currentSize+"--totalSize="+totalSize+"--progress="+progress+"--networkSpeed="+networkSpeed);


                            CommonEventBus<Float> commonEventBus=new CommonEventBus<>(TAG, AboutActivity.TAG,0,null);
                            commonEventBus.setContent(progress);
                            EventBus.getDefault().post(commonEventBus);

                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            isDownLoading=false;
                            LogUtils.i(TAG,"----下载出错---");
                        }
                    });



                }


            }
        }


        return super.onStartCommand(intent, flags, startId);
    }




    public boolean judgeFileDownLoaded(UpdateVersionBean updateVersionBean,File apkFile){




        //說明sd卡中存在此文件了

        int currentVerCode = AppUtils.getVersionCode(this.getBaseContext());

        int apkVerCode=AppUtils.getApkCode(this,apkFile.getAbsolutePath());

        int serversVerCode = NumUtils.string2Int(updateVersionBean.getVerCode());

        LogUtils.i(TAG,"serversVerCode="+serversVerCode+"---currentVerCode="+currentVerCode+"---apkVerCode="+apkVerCode);

        if (apkVerCode>=serversVerCode && currentVerCode<apkVerCode){
            return true;
        }

        return false;

    }






    private String getDownLoadFilePath(UpdateVersionBean updateVersionBean){
        String p=updateVersionBean.getFileName();
        String dl="http://o.ebelter.com/apk_update/temperaturegun_apk/";
        return addEndWith(dl+p,".apk");
    }

    private static String apkPath="/temApks/";
    private File getSaveApk(UpdateVersionBean updateVersionBean){
        String sdPath= FileUtils.getSDPath();
        File file=new File(sdPath+apkPath+addEndWith(updateVersionBean.getFileName(),".apk"));
        return file;
    }


    private String addEndWith(String p,String end){
        if (!p.endsWith(end)){
            return p+end;
        }
        return p;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    //开始执行安装: /storage/emulated/0/download/ehc_v1.2.5.apk
//    private void install(String filePath) {
//        LogUtils.i(TAG, "开始执行安装: " + filePath);
//        File apkFile = new File(filePath);
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            LogUtils.i(TAG, "版本大于 N ，开始使用 fileProvider 进行安装");
//            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            Uri contentUri = FileProvider.getUriForFile(
//                    this
//                    , "com.ebelter.ehc.fileprovider"
//                    , apkFile);
//            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
//        } else {
//            LogUtils.i(TAG, "正常进行安装");
//            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
//        }
//        startActivity(intent);
//    }

}
